package cn.sfrog.project.biz.applet.service.impl;

import cn.hutool.http.HttpUtil;
import cn.sfrog.common.core.domain.ApiAjaxResult;
import cn.sfrog.common.core.domain.entity.SysUser;
import cn.sfrog.common.utils.DateUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.project.biz.admin.domain.BizUserAccount;
import cn.sfrog.project.biz.admin.mapper.BizUserAccountMapper;
import cn.sfrog.project.biz.admin.service.IBizUserInviteRecordService;
import cn.sfrog.project.biz.applet.entity.AppCompanyEntity;
import cn.sfrog.project.biz.applet.entity.VO.*;
import cn.sfrog.project.biz.applet.mapper.AppExtOderMapper;
import cn.sfrog.project.biz.applet.service.AppExtOderService;
import cn.sfrog.project.biz.applet.utils.HttpClientUtil;
import cn.sfrog.project.biz.applet.utils.HttpPostGetUtil;
import cn.sfrog.system.mapper.SysUserMapper;
import cn.sfrog.system.service.ISysUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author chen
 * @Date 2023-12-01 16:34
 * @title AppExtOderServiceImpl
 * @description
 **/
@Slf4j
@Service
public class AppExtOderServiceImpl implements AppExtOderService{
    @Autowired
    private AppExtOderMapper appExtOderMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    ISysUserService userService;
    @Autowired
    private BizUserAccountMapper bizUserAccountMapper;
    @Autowired
    private IBizUserInviteRecordService bizUserInviteRecordService;
    @Override
    public ApiAjaxResult receiveExternalOrder(AppcompanyVo appcompanyVo) {
        SysUser sysUser = null;
        sysUser = userMapper.selectAppUserByPhone(appcompanyVo.getContactPhone());
        if (sysUser == null){
            SysUser newUser = new SysUser();
            //  注册
            newUser.setUserName(appcompanyVo.getContactPhone());
            newUser.setNickName(appcompanyVo.getContactName());
            newUser.setPhonenumber(appcompanyVo.getContactPhone());
            newUser.setCreateBy("admin");
            userService.insertUser(newUser);
            sysUser = userMapper.selectAppUserByPhone(appcompanyVo.getContactPhone());
            //  创建用户账户信息
            BizUserAccount bizUserAccount = new BizUserAccount();
            bizUserAccount.setUserId(sysUser.getUserId());
            bizUserAccount.setCreateTime(DateUtils.getNowDate());
            bizUserAccount.setUpdateTime(DateUtils.getNowDate());
            bizUserAccount.setCreateBy("admin");
            bizUserAccount.setUpdateBy("admin");
            bizUserAccountMapper.insert(bizUserAccount);
            //  创建邀请记录
            //  获取陪依创始人
            SysUser UserInfo = userMapper.selectAppUserByPhone("18662621080");
            bizUserInviteRecordService.creatUserInviteRecord(UserInfo.getUserId(),sysUser.getUserId());
        }
        int i = appExtOderMapper.receiveExternalOrder(appcompanyVo);
        return ApiAjaxResult.success();
    }

    @Override
    public int updataExternalOrder(AppCompanyEntity appCompanyEntity) {

        return appExtOderMapper.updataExternalOrder(appCompanyEntity);
    }

    @Override
    public ApiAjaxResult delExternalOrder(String serviceOrderSn) {
        int i = appExtOderMapper.delExternalOrder(serviceOrderSn);
        if (i != 1){
            return ApiAjaxResult.success("删除失败");
        }
        return ApiAjaxResult.success("删除成功");
    }

    @Override
    public List<AppCompanyEntity> externalOrderList() {
        List<AppCompanyEntity> appCompanyEntities = appExtOderMapper.externalOrderList();
        return appCompanyEntities;
    }

    @Override
    public ApiAjaxResult getExternalAcceptOrderStatus(String serviceOrderSn) {
        ExternalAcceptOrderVo externalAcceptOrderStatus = appExtOderMapper.getExternalAcceptOrderStatus(serviceOrderSn);
        if (externalAcceptOrderStatus != null){
            if (StringUtils.isNotEmpty(externalAcceptOrderStatus.getAcceptUserName())){
                return ApiAjaxResult.success(externalAcceptOrderStatus);
            }
        }
        return ApiAjaxResult.success("该订单暂未分配陪诊人员");
    }

    @Override
    public ApiAjaxResult confirmAccompanying(ConfirmAccompanyVO confirmAccompanyVO) {
        //  订单号 陪诊id 陪诊姓名 陪诊电话
        //  获取订单
        ExternalAcceptOrderVo externalAcceptOrderStatus = appExtOderMapper.getExternalAcceptOrderStatus(confirmAccompanyVO.getServiceOrderSn());
        //  confirmAccompanyVO
        if (externalAcceptOrderStatus != null){
            if(String.valueOf(externalAcceptOrderStatus.getAcceptUserId()).equals(confirmAccompanyVO.getAcceptUserId()) ){
                if (externalAcceptOrderStatus.getOrderStatus().equals("2")){
                    // 修改订单状态
                    int i = appExtOderMapper.updateExternalAcceptOrderStatus(confirmAccompanyVO);
                    if(i>0){
                        return ApiAjaxResult.success("陪诊订单确定");
                    }else{
                        return ApiAjaxResult.success("订单提交失败");
                    }
                }
            }
        }
        return ApiAjaxResult.success("该订单暂未分配陪诊人员");
    }

    @Override
    public ApiAjaxResult changeExternalOrderStatus(AppCompanyStatusVo appCompanyStatusVo) {
        int i = appExtOderMapper.changeExternalOrderStatus(appCompanyStatusVo);
        return ApiAjaxResult.success();
    }

    @Override
    public ApiAjaxResult shandongOrderPushAccompany(ShandongOrderPushAccompanyVo shandongOrderPushAccompanyVo) {
        ExternalAcceptOrderVo externalAcceptOrderStatus = appExtOderMapper.getExternalAcceptOrderStatus(shandongOrderPushAccompanyVo.getOrderSn());
        // 通过订单号
        Map map = new LinkedHashMap<>();
        map.put("orderSn",shandongOrderPushAccompanyVo.getOrderSn());
        map.put("status",shandongOrderPushAccompanyVo.getStatus());
        map.put("escortName",shandongOrderPushAccompanyVo.getEscortName());
        map.put("escortPhone",shandongOrderPushAccompanyVo.getEscortPhone());
        JSONObject jsonObject1 = new JSONObject(map);

        long millis = System.currentTimeMillis()/1000;
        UUID uuid = UUID.randomUUID();
        TreeMap<String, String> params = new TreeMap<>();
        params.put("app-id", "pyw0531");
        params.put("body", jsonObject1.toJSONString());
        params.put("req-id", uuid.toString());
        params.put("secret", "ed1fc39091a888869bfbe91b11a94713");
        params.put("timestamp", String.valueOf(millis));
        params.put("version", "1");
        StringBuilder builder = new StringBuilder();
        params.forEach((key, val) -> {
            builder.append(key).append("=").append(val);
            if (!org.apache.commons.lang3.StringUtils.equals(params.lastKey(), key)) {
                builder.append("&");
            }
        });
        String sign= DigestUtils.md5Hex(builder.toString()).toLowerCase();
        params.put("sign", sign);
        JSONObject jsonObject = null;
        try {
            String jsonStr = HttpPostGetUtil.httpPostJson("https://mall.sypm.cn/admin/api/escort/sync-order-info/", jsonObject1.toJSONString(), params);
            jsonObject = JSONObject.parseObject(jsonStr);
            if ("订单查询异常，请联系管理员！".equals(jsonObject.get("msg")) & jsonObject.get("code").toString().equals("500")){
                return ApiAjaxResult.error("山东订单查询异常，请稍后再试!");
            }
            System.out.println(jsonObject.get("msg"));
            System.out.println("json"+jsonObject);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (jsonObject.get("code").toString().equals("0")){
            if (externalAcceptOrderStatus.getOrderStatus().equals("1")){
                shandongOrderPushAccompanyVo.setStatus("2");
                int i = appExtOderMapper.shandongOrderPushAccompany(shandongOrderPushAccompanyVo);
            }else if(externalAcceptOrderStatus.getOrderStatus().equals("2")){
                //  订单已完成
                shandongOrderPushAccompanyVo.setStatus("5");
                int i = appExtOderMapper.shandongOrderPushAccompany(shandongOrderPushAccompanyVo);
            }else {
                return ApiAjaxResult.error("操作失败，请核对订单状态！");
            }
            return ApiAjaxResult.success("数据推送成功");
        }else{
            return ApiAjaxResult.error(jsonObject.get("code").toString(),jsonObject.get("msg").toString());
        }
    }
}
